package com.neusoft.bizcore.web.websocket;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import com.neusoft.bizcore.web.config.BizcoreWebProperties;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@ConditionalOnClass(WebSocketMessageBrokerConfigurer.class)
@ConditionalOnProperty(name = "bizcore.web.websocket.enable", havingValue = "true")
public class StompMessageService {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private BizcoreWebProperties properties;

    public void boardcast(final String channel, final Object msg) {
        this.messagingTemplate.convertAndSend(this.properties.getWebsocket().getBroadcaMessagePrefix() + channel,
                msg);
    }

    public void p2p(final String channel, final Object msg, final List<String> users) {
        users.forEach(user -> {
            try {
                this.messagingTemplate.convertAndSendToUser(user,
                        this.properties.getWebsocket().getP2pMessagePrefix() + channel,
                        msg);
            } catch (final Exception e) {
                StompMessageService.log.error(e.getMessage(), e);
            }
        });

    }

}
